<html>
  <head>
  </head>
  <body>
    <script>
      function getCurrentModel() {
          var currentstr = localStorage["model"];
          if (!currentstr) {
            return;
          }
          return JSON.parse(currentstr);
      };
      
      /**
       * Performs an XMLHttpRequest to TSA's API to post the tweet and category.
       * @param callback Function If the response from fetching url has a
       *     HTTP status of 200, this function is called with a JSON decoded
       *     response.  Otherwise, this function is called with null.
       */
      function postTweet(tweet, callback) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(data) {
          if (xhr.readyState == 4) {
            if (xhr.status == 200) {
              console.log("status:" + xhr.responseText);
              var data = JSON.parse(xhr.responseText);
              console.log("responseText:" + xhr.responseText);
              callback(data);
            } else {
              callback({"status": xhr.status});
            }
          }
        };
        // Note that any URL fetched here must be matched by a permission in
        // the manifest.json file!
        var host = localStorage["host"];
        var url = host + 'model/' + getCurrentModel().id + '/post';
        console.log("json received:" + JSON.stringify(tweet));
        var formData = "tweet-id=" + tweet.tId + "&" +
                     "tweet-lang=" + tweet.tLang + "&" +
                     "tweet-href=" + tweet.tHref + "&" +
                     "tweet-text=" + encodeURIComponent(tweet.tText) + "&" +
                     "tweet-cat=" + tweet.tCat;
        console.log("formData:" + formData);
//        var formData = new FormData();
//        formData.append("tweet-id", tweet.tweet-id);
//        formData.append("tweet-lang", tweet.tweet-lang);
//        formData.append("tweet-text", tweet.tweet-text);
        console.log("before post");
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.withCredentials = "true";
        xhr.send(formData);
      };

//                queries = [(x['iso_language_code'], x['text']) for x in tweets]
      function classifyTweet(tweet, callback) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(data) {
          if (xhr.readyState == 4) {
            if (xhr.status == 200) {
              console.log("status:" + xhr.responseText);
              var data = JSON.parse(xhr.responseText);
              console.log("responseText:" + xhr.responseText);
              callback(data);
            } else {
              callback({"status": xhr.status});
            }
          }
        };
        // Note that any URL fetched here must be matched by a permission in
        // the manifest.json file!
        var host = localStorage["host"];
        var url = host + 'classify/' + getCurrentModel().id;
        var data = JSON.stringify(tweet);
        console.log("json sent to classify:" + data);
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.withCredentials = "true";
        xhr.send(data);
      };

      function getPrefs(request, callback) {
          var currentStr = localStorage["model"];
          console.log(currentStr);
          var currentModel = JSON.parse(currentStr);
          callback(currentModel);
      };

      /**
       * Handles data sent via chrome.extension.sendRequest().
       * @param request Object Data sent in the request.
       * @param sender Object Origin of the request.
       * @param callback Function The method to call when the request completes.
       */
      function onRequest(request, sender, callback) {
        // Only supports the 'fetchTwitterFeed' method, although this could be
        // generalized into a more robust RPC system.
        console.log(request.action);
        if (request.action == 'postTweet') {
          postTweet(request.tweet, callback);
        }
        if (request.action == 'classifyTweet') {
          classifyTweet(request.tweet, callback);
        }
        if (request.action == 'getPrefs') {
          getPrefs(request, callback);
        }
      };

      // Wire up the listener.
      chrome.extension.onRequest.addListener(onRequest);
    </script>
  </body>
</html>
